<template>
  <el-dialog
    v-model="dialogTableVisible5"
    :show-close="true"
    width="60%"
    style="z-index: 100"
  >
    <div style="height: 465px; overflow: hidden">
      <div style="top: 5px">
        <el-input style="width: 150px; margin-left: 2px" v-model="ID" placeholder="id">
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 150px; margin-left: 2px"
          v-model="tableName"
          placeholder="表名"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>

        <el-button style="margin-left: 5px" @click="geSysStatus" type="primary"
          >查询</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData5"
          @row-click="RowClick5"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="420px"
          height="420px"
          @selection-change="handleSelectionChange"
          show-overflow-tooltip
        >
          <el-table-column fixed type="index" width="60" align="center" />
          <el-table-column fixed type="selection" width="50" align="center" />
          <el-table-column fixed prop="id" label="id" width="50" align="center" />
          <el-table-column
            prop="equipmentName"
            label="设备名称"
            width="100"
            align="center"
          />
          <el-table-column
            prop="equipmentCode"
            label="设备编码"
            width="100"
            align="center"
          />
          <el-table-column
            prop="equipmentStatus"
            label="设备状态"
            width="100"
            align="center"
          />
          <el-table-column prop="description" label="说明" width="100" align="left" />
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="page2"
            v-model:page-size="limit2"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total5"
            @size-change="handleSizeChange5"
            @current-change="handleCurrentChange5"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <!--dialog5-->
  <el-dialog v-model="dialogTableVisible4" :show-close="true" width="60%">
    <div style="height: 465px; overflow: hidden">
      <div style="position: absolute; top: 5px">
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="inputK3Bm"
          placeholder="k3编码"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="inputK3Mc"
          placeholder="k3名称"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-button
          style="margin-left: 5px"
          @click="searc3Kh"
        
          type="primary"
          >查询</el-button
        >
        <el-button
          style="margin-left: 5px"
          @click="put3Kh"
          v-if="put3KhPermissions7"
          type="primary"
          >添加</el-button
        >
        <el-button
          style="margin-left: 5px"
          @click="updateK3"
          v-if="updateK3Permissions7"
          type="success"
          >更新k3</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData3"
          @row-click="RowClick3"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="420px"
          height="420px"
          @selection-change="handleSelectionChange1"
          show-overflow-tooltip
        >
          <el-table-column fixed type="index" width="60" align="center" />
          <el-table-column fixed type="selection" width="50" align="center" />
          <el-table-column fixed prop="id" label="id" width="120" align="center" />
          <el-table-column
            prop="uniqueCode"
            label="单件唯一码"
            width="120"
            align="center"
          />
          <el-table-column prop="componentId" label="零件ID" width="120" align="center" />
          <el-table-column
            prop="materialStatus"
            label="物料状态"
            width="200"
            align="center"
          />
          <el-table-column
            prop="materialCode"
            label="物料编码"
            width="200"
            align="center"
          />
          <el-table-column
            prop="supplierUniqueCode"
            label="供应商唯一码"
            width="200"
            align="center"
          />
          <el-table-column prop="isdel" label="状态" width="200" align="center" />
        </el-table>

        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="page2"
            v-model:page-size="limit2"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total3"
            @size-change="handleSizeChange3"
            @current-change="handleCurrentChange3"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <el-dialog
    v-model="dialogTableVisible2"
    :show-close="true"
    width="60%"
    style="z-index: 100"
  >
    <div style="height: 465px; overflow: hidden">
      <div style="top: 5px">
        <el-input style="width: 150px; margin-left: 2px" v-model="ID" placeholder="id">
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 150px; margin-left: 2px"
          v-model="tableName"
          placeholder="表名"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>

        <el-button style="margin-left: 5px" @click="geSysStatus" type="primary"
          >查询</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData2"
          @row-click="RowClick2"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="420px"
          height="420px"
          @selection-change="handleSelectionChange2"
          show-overflow-tooltip
        >
          <el-table-column fixed type="index" width="80" align="center" />
          <el-table-column fixed type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" width="70" align="center" />

          <el-table-column prop="name" label="设备零件" width="140" align="center" />
          <el-table-column
            prop="structureName"
            label="设备结构"
            width="120"
            align="center"
          />
          <el-table-column
            prop="consumableCategoryName"
            label="耗材类别"
            width="120"
            align="center"
          />
          <el-table-column prop="model" label="型号" width="120" align="center" />

          <el-table-column
            prop="consumableCategoryName"
            label="耗材类别"
            width="120"
            align="center"
          />

          <el-table-column prop="creator" label="创建人" width="120" align="center" />
          <el-table-column prop="reviewer" label="审核人" width="120" align="center" />
          <el-table-column prop="modifier" label="修改人" width="120" align="center" />
          <el-table-column prop="stateName" label="状态" width="120" align="center" />
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="page2"
            v-model:page-size="limit2"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total2"
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 添加 -->

  <div
    v-if="dialogTableVisible"
    :width="screenWidth + 20 + 'px'"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 80;

      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div
      :style="{
        width: screenWidth - 96.5 + 'px',
        backgroundColor: 'white',
        zIndex: 8001,
      }"
    >
      <div
        :style="{
          height: screenHeight - 43.5 + 'px',
          borderBottom: '1px solid #ccc',
          width: '100%',
          backgroundColor: 'white',
          zIndex: 8002,
          display: 'flex',
          flexDirection: 'column',
        }"
      >
        <div
          ref="buttonDiv"
          style="
            background-color: white;
            z-index: 82;
            display: flex;
            margin-left: auto;
            height: 32px;
          "
        >
          <el-button @click="addRow" v-if="addRowPermissions8" type="primary"
            >增行</el-button
          >
          <el-button @click="getDeleteRowData" type="danger">删除</el-button>
          <el-button type="primary" @click="insertMaterialsFixed">保存</el-button>
          <el-button type="primary" @click="updateMaterialsFixed">修改</el-button>
          <el-button @click="OFFdialogTableVisible" type="danger">关闭</el-button>
        </div>
        <div
          ref="mBeginDiv"
          :style="{
            backgroundColor: 'rgba(247, 247, 247, 0.903)',
            height: 65 + 'px',
            width: screenWidth - 96.5 + 'px',
          }"
        >
          <el-form :model="form" class="demo-form-inline" :inline="true">
            <el-form-item class="labs" style="margin-right: 0">
              <label
                class="lab"
                style="width: 100px; padding-right: 5px; padding-left: 21px"
                >快捷录入</label
              >
              <t-select-table
                ref="selectTable"
                :row-style="rowState1"
                :cell-style="cellStyle1"
                :header-cell-style="headerCellStyle1"
                :table="stateTable.table"
                :columns="stateTable.table.columns"
                :max-height="600"
                :keywords="{ label: 'uniqueCode', value: 'uniqueCode' }"
                isShowPagination
                isKeyup
                isExpanded
                :filter-method="filterMethod"
                @radioChange="radioChange"
                @blur="handleBlurTable"
                @page-change="pageChange"
                :selectWidth="150"
                :tableWidth="490"
              ></t-select-table>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">精确查询</label>
              <t-select-table
                ref="selectTable1"
                :row-style="rowState1"
                :cell-style="cellStyle1"
                :header-cell-style="headerCellStyle1"
                :table="stateTable1.table"
                :columns="stateTable1.table.columns"
                :max-height="600"
                :keywords="{ label: 'uniqueCode', value: 'uniqueCode' }"
                isShowPagination
                isKeyup
                isExpanded
                :filter-method="filterMethod1"
                @radioChange="radioChange1"
                @blur="handleBlurTable1"
                @page-change="pageChange1"
                :selectWidth="150"
                :tableWidth="490"
              ></t-select-table>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px"
                ><span style="color: red">*</span>单据状态</label
              >
              <el-select
                v-model="form.djStatus"
                size="medium"
                style="width: 100px"
                clearable
              >
                <el-option label="未审核" value="0"></el-option>
                <el-option label="已审核" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px"
                ><span style="color: red">*</span>异常状态</label
              >
              <el-select
                v-model="form.exceptionMode"
                size="medium"
                style="width: 100px"
                clearable
              >
                <el-option label="搁置" value="3"></el-option>
                <el-option label="异常" value="4"></el-option>
                <el-option label="报废" value="5"></el-option>
              </el-select>
            </el-form-item>
            <el-form :model="form" class="demo-form-inline" :inline="true">
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 120px; padding-right: 5px"
                  ><span style="color: red">*</span>异常原因</label
                >
                <el-input
                  style="width: 610px"
                  v-model="form.abnormalCause"
                  placeholder=""
                  clearable
                />
              </el-form-item>
            </el-form>
          </el-form>
        </div>
        <el-form :inline="true" :model="formInline">
          <div
            ref="headerTable"
            :style="{
              width: screenWidth - 96.5 + 'px',
              // height: 720+ 'px',
              'overflow-y': 'hidden',
              'overflow-x': 'hidden',
              'scrollbar-width': 'thin',
            }"
          >
            <table style="height: 35px; width: 100%">
              <tr class="sticky-header" style="z-index: 99">
                <th style="width: 50px" class="table-header">序号</th>
                <th style="width: 50px" class="table-header">
                  <el-checkbox
                    @change="toggleSelectAll"
                    v-model="selectAll"
                  ></el-checkbox>
                </th>
                <th style="width: 100px" class="table-header">单件唯一码</th>
                <th style="width: 100px" class="table-header">材质</th>
                <th style="width: 100px" class="table-header">规格</th>
                <th style="width: 100px" class="table-header">型号</th>
                <th style="width: 100px" class="table-header">粗糙度</th>
                <th style="width: 100px" class="table-header">磨削总量</th>
                <th style="width: 100px" class="table-header">剩余磨削量</th>
                <th style="width: auto" class="table-header">说明</th>
                <th style="width: 80px" class="table-header">操作</th>
              </tr>
            </table>
          </div>
          <div
            ref="subDataDiv"
            :style="{
              height: calculatedHeight + 'px',
              width: screenWidth - 96.5 + 'px',
              'overflow-y': 'scroll',
              'overflow-x': 'auto',
              'scrollbar-width': 'thin',
            }"
          >
            <table id="subDataTbale" style="width: 100%">
              <tr
                v-for="(formData, index) in formDataList"
                :key="index"
                style="height: 30px"
              >
                <td class="sticky-column" style="text-align: center; width: 50px">
                  {{ index + 1 }}
                </td>
                <td style="text-align: center; width: 50px">
                  <el-checkbox v-model="formData.selected"></el-checkbox>
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <div
                    style="height: 25px; line-height: 25px; cursor: pointer"
                    @click="openWlbm(index)"
                  >
                    {{ formData.uniqueCode }}
                  </div>
                </td>

                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <div style="height: 25px; line-height: 25px" @click="openWlbm(index)">
                    {{ formData.material }}
                  </div>
                </td>

                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <div style="height: 25px; line-height: 25px" @click="openWlbm(index)">
                    {{ formData.specification }}
                  </div>
                </td>

                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <div style="height: 25px; line-height: 25px" @click="openWlbm(index)">
                    {{ formData.model }}
                  </div>
                </td>

                <!-- <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-input
                    @click="openWlbm(index)"
                    v-model="formData.uniqueCode"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.material"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.specification"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.model"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td> -->
                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.roughnessStandard"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.totalGrindingAmount"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.residualGrindingCapacity"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td>
                <td
                  class="table-value"
                  style="width: auto; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.comment"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                </td>
                <td
                  class="sticky-column"
                  style="width: 70px; text-align: left; padding-left: 1px; fixed: right"
                >
                  <el-button
                    style="width: auto; margin-top: 1px"
                    type="danger"
                    @click="handleDeletes(index)"
                    >删除</el-button
                  >
                </td>
              </tr>
            </table>
          </div>

          <div
            ref="footerDiv"
            :style="{
              width: screenWidth - 96.5 + 'px',
            }"
          >
            <table style="height: 35px">
              <tr
                style="
                  text-align: center;
                  position: sticky;
                  bottom: -1px;
                  background-color: #ddd;
                  z-index: 99;
                "
              >
                <td style="width: 50px; text-align: left">合计:</td>
                <td style="width: 50px; text-align: left; padding-left: 1px"></td>
                <td style="width: 50px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 73px; text-align: left; padding-left: 1px"></td>
                <td style="width: 80px; text-align: left; padding-left: 1px"></td>
              </tr>
            </table>
          </div>
        </el-form>
        <div ref="mEndDiv" style="background-color: rgba(247, 247, 247, 0.903)">
          <el-form
            :model="form"
            class="demo-form-inline"
            :inline="true"
            :style="{
              backgroundColor: ' rgba(247, 247, 247, 0.903)',
              width: screenWidth - 96.5 + 'px',
              height: '50px',
            }"
          >
            <el-form-item class="lab" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">备注</label>
              <el-input
                :style="{
                  width: screenWidth - 96.5 - 100 - 5 + 'px',
                  zIndex: '99',
                  backgroundColor: '#ffffff',
                  resize: 'none',
                  height: '45px',
                }"
                type="textarea"
                v-model="form.bz"
                placeholder="备注"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">制单人</label>
              <el-input
                v-model="form.zdr"
                style="width: 200px; height: 35px"
                disabled
                placeholder="制单人"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">制单时间</label>
              <el-config-provider :locale="locale">
                <el-date-picker
                  style="width: 200px"
                  disabled
                  v-model="form.zdsj"
                  type="datetime"
                  placeholder="制单时间"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">修改人</label>
              <el-input
                style="width: 180px"
                v-model="form.xgr"
                disabled
                placeholder="修改人"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">修改时间</label>
              <el-config-provider :locale="locale">
                <el-date-picker
                  style="width: 200px"
                  disabled
                  v-model="form.xgsj"
                  type="datetime"
                  placeholder="修改时间"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">审核人</label>
              <el-input
                style="width: 200px"
                v-model="form.shr"
                disabled
                placeholder="审核人"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0; height: 3.5vh">
              <label class="lab" style="width: 100px; padding-right: 5px"
                >审核时间:</label
              >
              <el-config-provider :locale="locale">
                <el-date-picker
                  style="width: 200px"
                  disabled
                  v-model="form.shsj"
                  type="datetime"
                  placeholder="审核时间"
                />
              </el-config-provider>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>

  <!-- 页面布局 -->
  <div>
    <el-container>
      <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
        <!-- 头部按钮 -->
        <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
          <div style="display: flex; align-items: center">
            <el-button @click="searchButton" type="primary"> 查询</el-button>
            <el-button @click="handleAudit" type="warning">审核</el-button>

            <el-button @click="handleAction1" type="success">新增</el-button>
            <el-button @click="handleDelete" type="danger">删除</el-button>
          </div>
          <!-- <div class="title">包材需求计算</div> -->
        </el-row>
        <div
          style="margin-left:5.6rem;height: 30px;width=100%; background:rgb(241,244,243);margin-bottom: 0;position: relative; display: flex; justify-content: flex-start;"
        >
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="id"
            placeholder="id"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="equipmentName"
            placeholder="设备名称"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-header>
      <el-container>
        <el-container>
          <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
            <el-table
              v-loading="loading"
              ref="table"
              :data="tableData"
              border
              stripe
              :header-cell-style="headerCellStyle"
              @selection-change="handleSelectionChange"
              @row-dblclick="handleRowClick"
              @row-click="RowClick"
              :row-style="rowState"
              :row-key="(row) => row.id"
              :max-height="screenHeight"
              :height="screenHeight - 135 + 'px'"
              empty-text="无数据"
            >
              <el-table-column fixed type="index" width="60" align="center" />
              <el-table-column fixed type="selection" width="50" align="center" />
              <el-table-column prop="djCode" label="单据号" width="120" align="center" />
              <el-table-column
                prop="exceptionMode"
                label="异常类型"
                width="120"
                align="center"
              />
              <el-table-column
                prop="djStatus"
                label="单据状态"
                width="200"
                align="center"
              />
              <el-table-column
                prop="applicant"
                label="申请人"
                width="100"
                align="center"
              />
              <el-table-column
                prop="applicationTime"
                label="申请时间"
                width="200"
                align="center"
              />
              <el-table-column
                prop="abnormalCause"
                label="异常原因"
                width="200"
                align="left"
              />
            </el-table>
          </el-main>
          <!-- <el-footer style="background: linear-gradient(to right, #f9f9fc, #fef5f0)"
            >Footer</el-footer
          > --><el-footer style="height: 20px">
            <div class="demo-pagination-block">
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="limit"
                :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
                :small="true"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-footer>
        </el-container>
        <!-- <el-aside width="20%"></el-aside> -->
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";
import * as notifications from "../../components/utils/notification.ts";

import Co from "../../components/utils/t-ui-plus-dev/packages/select-table/src/index.vue";
const Permission = ref(false);
const isDdslDisabledYwy = ref(true);
const router = useRouter();
const isDdslDisabled = ref(true);
// 权限控制
const searbzfaPermissions8 = ref(false);
const searchYwyPermissions8 = ref(false);
const updatYwyPermissions8 = ref(false);
const addRowPermissions8 = ref(false);
const getDeleteRowDataPermissions8 = ref(false);
const insertMaterialsFixedPermissions8 = ref(false);
const updateMaterialsFixedPermissions8 = ref(false);
const OFFdialogTableVisiblePermissions8 = ref(false);
const searchButtonPermissions8 = ref(false);
const handleAction1Permissions8 = ref(false);
const handleWarning0Permissions8 = ref(false);
const handleWarning1Permissions8 = ref(false);
const handleDeletePermissions8 = ref(false);
const menuId = ref(8);
const buttonVariables = {
  searbzfaPermissions8,
  searchYwyPermissions8,
  updatYwyPermissions8,
  addRowPermissions8,
  getDeleteRowDataPermissions8,
  insertMaterialsFixedPermissions8,
  updateMaterialsFixedPermissions8,
  OFFdialogTableVisiblePermissions8,
  searchButtonPermissions8,
  handleAction1Permissions8,
  handleWarning0Permissions8,
  handleWarning1Permissions8,
  handleDeletePermissions8,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");

  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();

const xxx = ref();

// 计算高度
const screenHeight = ref(null);
const dynamicHeight = ref(null);
const dynamicHeightYtfl = ref(null);
const tableHeight = ref(null);

const getScreenHeight = () => {
  screenHeight.value = window.innerHeight - 146 - 42 + 55;
  dynamicHeight.value = `${window.innerHeight - 55 + 55}px`;
  dynamicHeightYtfl.value = window.innerHeight - 120 + 55;
  tableHeight.value = window.innerHeight - 435 + 19 + 55;

  console.log("高度");
  console.log("子表:" + tableHeight.value);
};
getScreenHeight();

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
const activeIndex = ref("1");
const handleSelect = (key: string, keyPath: string[]) => {};
const dialogTableVisible = ref(false);
const dialogTableVisible1 = ref(false);
const dialogTableVisible2 = ref(false);
const dialogTableVisible3 = ref(false);
const dialogTableVisible4 = ref(false);
const dialogTableVisible5 = ref(false);
//声明类
const formInline = ref([]);
const ddslinput = ref(null);
const isPrinting = ref(false);
const equipmentName = ref("");
const selectedRows = ref([]);
const id = ref("");
const tableName = ref("");
const status = ref("");
const categoryOfConsumables = ref("");
const djStatus = ref("");
const direction = ref("");
const wlbm = ref("");
const ID = ref("");
const singleStatus = ref("");
const isdel = ref("");
const materialCode = ref("");
const supplierUniqueCode = ref("");
const businessProjectId = ref("");
const itemType = ref("");
const parameterItemId = ref("");
const itemCode = ref("");
const itemName = ref("");
const valueRangeType = ref("");
const sourceMethod = ref("");
const sourcePrimaryKeyField = ref("");
const standardValueField = ref("");
const lowerLimitField = ref("");
const upperLimitField = ref("");
const verticalLine3 = ref(null);
const tableData = ref([]);
const tableData1 = ref([]);
const tableData3 = ref([]);
const tableData4 = ref([]);
const tableData5 = ref([]);
const checkList = ref([]);
const checkList1 = ref([]);
const showInsertButton = ref(true);
const screenWidth = ref(window.innerWidth);

const inputHeight = ref(200);
// 头部按钮
const table = ref();
const rowTable = ref([]);
//子表
let selectedRowIndex = -1; // 初始化为-1，表示没有选中的行
let clearSelection = true;
//多选
const selectAll = ref(false);
// 分页
const page = ref(1);
const page1 = ref(1);
const page2 = ref(1);
const page3 = ref(1);
const page4 = ref(1);
const page5 = ref(1);
const limit = ref(50);
const limit1 = ref(50);
const limit2 = ref(50);
const limit3 = ref(50);
const limit4 = ref(50);
const limit5 = ref(50);
const total = ref(10);
const total1 = ref(10);
const total2 = ref(10);
const total3 = ref(10);
const total4 = ref(10);
const total5 = ref(10);
const loading = ref(false);

// // 设置表头样式
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  textAlign: "center",
  // padding: "0 0 0 30px",
};
//方法类
const selectCookies = () => {};
selectCookies();
const handleResize = () => {
  screenWidth.value = window.innerWidth;
  console.log("宽度" + screenWidth.value);
  // screenWidth.value = screenWidth.value - 96;
  screenHeight.value = window.innerHeight;
  inputHeight.value = 50;
  console.log(screenHeight.value + "高度1");
};
handleResize();
const handleRowClick = async (row) => {
  await getData(stateTable.table.currentPage);
  // isDdslDisabled.value = false;
  // isDdslDisabledYwy.value = true;
  dialogTableVisible.value = true;
  showInsertButton.value = false;
  form.id = row.djCode;
  form.djCode = row.djCode;
  form.djStatus = row.djStatus;
  form.exceptionMode = row.exceptionMode;
  form.abnormalCause = row.abnormalCause;
  const userName = Cookies.get("userName");
  const currentFormattedDateTime = getCurrentFormattedDateTime();
  const currentFormattedDate = getCurrentFormattedDate();
  form.xgsj = currentFormattedDateTime;
  form.xgr = userName;
  nextTick(() => {
    const height = buttonDiv.value.clientHeight;
    const height1 = mBeginDiv.value.clientHeight;
    const height2 = headerTable.value.clientHeight;
    const height3 = subDataDiv.value.clientHeight;
    const height4 = footerDiv.value.clientHeight;
    const height5 = mEndDiv.value.clientHeight;
    const totalHeight = document.body.scrollHeight;
    console.log(
      "buttonDiv" + height,
      "mBeginDiv" + height1,
      "headerTable" + height2,
      "subDataDiv" + height3,
      "footerDiv" + height4,
      "mEndDiv" + height5,
      "totalHeight" + totalHeight
    );
    const heightSum = height + height1 + height2 + height4 + height5;

    const calculatedHeight = totalHeight - heightSum - 75;
    subDataDiv.value.style.height = `${calculatedHeight}px`;

    console.log("Calculated height:", calculatedHeight);
  });
  // 回显测算类型
  // 回显子表
  axios({
    url: "/Abn/select/AbnormalSubTable",
    method: "post",
    data: {
      id: form.djCode,
    },
  }).then((res) => {
    const testList = res.data;
    console.log(testList);

    if (testList.length === 0) {
      for (let a = 0; a < 21; a++) {
        addRow();
      }
    } else {
      const formattedData = testList.map((test, index) => ({
        autoId: test.autoId,
        id: test.id,
        mid: test.mid,
        componentId: test.componentId,
        equipmentStructureId: test.equipmentStructureId,
        material: test.material,
        specification: test.specification,
        model: test.model,
        uniqueCode: test.uniqueCode,
        totalGrindingAmount: test.totalGrindingAmount,
        residualGrindingCapacity: test.residualGrindingCapacity,
        roughnessStandard: test.roughnessStandard,
        comment: test.comment,
      }));
      formDataList.value = formattedData;
    }
    console.log(formDataList.value);
  });
};
const handleBlur = (fieldName, rowIndex) => {
  const form = formDataList.value[rowIndex];
  const val = form[fieldName];
  validateAndFormat(form, fieldName, val);
};
const validateAndFormat = (form, prop, val) => {
  if (!isNaN(parseFloat(val)) && isFinite(val)) {
    // 将数字保留四位小数
    form[prop] = parseFloat(val).toFixed(2);
  } else {
    // 如果不是有效数字，清空表单
    form[prop] = "";
  }
};
const buttonDiv = ref();
const mBeginDiv = ref();
const headerTable = ref();
const subDataDiv = ref();
const footerDiv = ref();
const mEndDiv = ref();
const calculatedHeight = ref(null);
const handleAction1 = function () {
  dialogTableVisible.value = true;
  isDdslDisabled.value = true;
  isDdslDisabledYwy.value = false;
  showInsertButton.value = true;

  nextTick(() => {
    const height = buttonDiv.value.clientHeight;
    const height1 = mBeginDiv.value.clientHeight;
    const height2 = headerTable.value.clientHeight;
    const height3 = subDataDiv.value.clientHeight;
    const height4 = footerDiv.value.clientHeight;
    const height5 = mEndDiv.value.clientHeight;
    const totalHeight = document.body.scrollHeight;
    console.log(
      "buttonDiv" + height,
      "mBeginDiv" + height1,
      "headerTable" + height2,
      "subDataDiv" + height3,
      "footerDiv" + height4,
      "mEndDiv" + height5,
      "totalHeight" + totalHeight
    );
    const heightSum = height + height1 + height2 + height4 + height5;

    const calculatedHeight = totalHeight - heightSum - 75;
    subDataDiv.value.style.height = `${calculatedHeight}px`;

    console.log("Calculated height:", calculatedHeight);
  });
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};

// 关闭弹窗
const OFFdialogTableVisible = () => {
  dialogTableVisible.value = false;
  showInsertButton.value = true;

  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  (checkList.value = ""), (checkList1.value = "");
  // 删除
  formDataList.value = [];
  // location.reload();
  page1.value = 1;
  page2.value = 1;
  page3.value = 1;
  page4.value = 1;
  page5.value = 1;
  limit1.value = 50;
  limit2.value = 50;
  limit3.value = 50;
  limit4.value = 50;
  limit5.value = 50;
};
// 进入页面
const selectpurposes = () => {
  // 查看是否登录
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  axios({
    url: "/Abn/select/AbnormalApplicationMain",
    method: "post",
    data: {
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    const testList = res.data;
    if (testList.length == 0) {
      loading.value = false;
      return;
    }
    total.value = res.data[0].total;

    tableData.value = testList.map((test) => ({
      // 根据 djzt 的值设置状态
      // zt: test.zt === 0 ? "待审" : "已审核",
      autoId: test.autoId,
      id: test.id,
      djCode: test.id,
      applicant: test.applicant,
      applicationTime: test.applicationTime,
      abnormalCause: test.abnormalCause,
      exceptionMode:
        test.exceptionMode == 3 ? "搁置" : test.exceptionMode == 4 ? "异常" : "报废",
      djStatus: test.djStatus == 0 ? "未审核" : "已审核",
    }));

    for (let a = 0; a < 20; a++) {
      addRow();
    }
    //制单人
    form.zdr = userName;
    // 制单时间
    const currentFormattedDateTime = getCurrentFormattedDateTime();
    const currentFormattedDate = getCurrentFormattedDate();
    form.zdsj = currentFormattedDateTime;
    loading.value = false;
  });
  loading.value = true;
};

const RowClick1 = (row, selection) => {
  form.testName = row.testName;
  dialogTableVisible1.value = false;
};
const formDataList = ref([
  {
    id: "",
    mid: "",
    uniqueCode: "",
    componentId: "",
    material: "",
    specification: "",
    equipmentStructureId: "",
    totalGrindingAmount: "",
    residualGrindingCapacity: "",
    roughnessStandard: "",
    model: "",
    comment: "",
    selected: false,
  },
]);
const form = reactive({
  id: "",
  abnormalCause: "",
  applicant: "",
  exceptionMode: "",
  applicationTime: "",
  djCode: "",
  djStatus: "0",
  zdr: "",
  zdsj: "",
  xgr: "",
  xgsj: "",
  shr: "",
  shsj: "",
});
const addRow = () => {
  formDataList.value.push({
    id: "",
    mid: "",
    uniqueCode: "",
    componentId: "",
    material: "",
    specification: "",
    equipmentStructureId: "",
    totalGrindingAmount: "",
    residualGrindingCapacity: "",
    roughnessStandard: "",
    model: "",
    comment: "",
    selected: false,
  });

  console.log(
    "网页可见区域宽：" + document.body.clientWidth,
    "网页可见区域高：" + document.body.clientHeight,
    "网页可见区域宽：" + document.body.offsetWidth,
    "网页可见区域高：" + document.body.offsetHeight,
    "网页正文全文宽：" + document.body.scrollWidth,
    "网页正文全文高：" + document.body.scrollHeight,
    "网页被卷去的高：" + document.body.scrollTop,
    "网页被卷去的左：" + document.body.scrollLeft,
    "网页正文部分上：" + window.screenTop,
    "网页正文部分左：" + window.screenLeft,
    "屏幕分辨率的高：" + window.screen.height,
    "屏幕分辨率的宽：" + window.screen.width,
    "屏幕可用工作区高度：" + window.screen.availHeight,
    "屏幕可用工作区宽度：" + window.screen.availWidth
  );
};
const getEquipment = () => {
  axios({
    url: "/select/EquipmentBasicInfoTable",
    method: "post",
    data: {
      ID: ID.value,
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    tableData5.value = res.data;
    if (res.data.length == 0) {
      total5.value == 0;
      return;
    }
    total5.value = res.data[0].total;
  });
};
const openEquipment = (index) => {
  indexK3bm = index;
  console.log(indexK3bm);
  dialogTableVisible5.value = true;
  getEquipment();
};
const handleSizeChange5 = (val: number) => {
  axios({
    url: "/select/EquipmentBasicInfoTable",
    method: "post",
    data: {
      ID: ID.value,
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    tableData5.value = res.data;
    if (res.data.length == 0) {
      total5.value == 0;
      return;
    }
    total5.value = res.data[0].total;
  });
};
const handleCurrentChange5 = (val: number) => {
  axios({
    url: "/select/EquipmentBasicInfoTable",
    method: "post",
    data: {
      page: page2.value,
      limit: limit2.value,
      ID: ID.value,
    },
  }).then((res) => {
    tableData5.value = res.data;
    if (res.data.length == 0) {
      total5.value == 0;
      return;
    }
    total5.value = res.data[0].total;
  });
};
const RowClick5 = (row, selection) => {
  form.equipment = row.equipmentName;
  form.equipmentId = row.id;
  dialogTableVisible5.value = false;
};
const tableData2 = ref([]);
var indexK3bm = 0;
const getK3vm = () => {
  axios({
    url: "/select/ComponentSingleRegistrationTable",
    method: "post",
    data: {
      ID: ID.value,
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    const definitionsList = res.data;
    if (res.data.length == 0) {
      total3.value = 0; // 这里已修正为赋值操作符 "="
      // 清空或重置tableData3的值，具体取决于你希望的展示效果
      tableData3.value = []; // 或者使用null、默认对象等，根据实际需求
      return;
    }
    total3.value = res.data[0].total;
    tableData3.value = definitionsList.map((item: any) => ({
      materialStatus:
        item.materialStatus === 0
          ? "初始登记"
          : item.materialStatus === 1
          ? "在用状态"
          : item.materialStatus === 2
          ? "搁置状态"
          : item.materialStatus === 3
          ? "报废状态"
          : item.materialStatus === 4
          ? "注销"
          : "其他",
      circulationState:
        item.circulationState === 1
          ? "待耗用"
          : item.materialStatus === 2
          ? "耗用中"
          : item.materialStatus === 3
          ? "待磨削"
          : item.materialStatus === 4
          ? "搁置"
          : item.materialStatus === 5
          ? "注销"
          : "其他",
      ...item,
    }));
  });
};
const openWlbm = (index) => {
  indexK3bm = index;
  console.log(indexK3bm);
  dialogTableVisible4.value = true;
  getK3vm();
};
const handleSizeChange3 = (val: number) => {
  axios({
    url: "/select/ComponentSingleRegistrationTable",
    method: "post",
    data: {
      ID: ID.value,
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    const definitionsList = res.data;
    if (res.data.length == 0) {
      total3.value == 0;
      return;
    }
    total3.value = res.data[0].total;
    tableData3.value = definitionsList.map((item: any) => ({
      materialStatus:
        item.materialStatus === 0
          ? "初始登记"
          : item.materialStatus === 1
          ? "在用状态"
          : item.materialStatus === 2
          ? "搁置状态"
          : item.materialStatus === 3
          ? "报废状态"
          : item.materialStatus === 4
          ? "注销"
          : "其他",
      circulationState:
        item.circulationState === 1
          ? "待耗用"
          : item.materialStatus === 2
          ? "耗用中"
          : item.materialStatus === 3
          ? "待磨削"
          : item.materialStatus === 4
          ? "搁置"
          : item.materialStatus === 5
          ? "注销"
          : "其他",
      ...item,
    }));
  });
};
const handleCurrentChange3 = (val: number) => {
  axios({
    url: "/select/ComponentSingleRegistrationTable",
    method: "post",
    data: {
      page: page2.value,
      limit: limit2.value,
      ID: ID.value,
    },
  }).then((res) => {
    const definitionsList = res.data;
    if (res.data.length == 0) {
      total3.value == 0;
      return;
    }
    total3.value = res.data[0].total;
    tableData3.value = definitionsList.map((item: any) => ({
      materialStatus:
        item.materialStatus === 0
          ? "初始登记"
          : item.materialStatus === 1
          ? "在用状态"
          : item.materialStatus === 2
          ? "搁置状态"
          : item.materialStatus === 3
          ? "报废状态"
          : item.materialStatus === 4
          ? "注销"
          : "其他",
      circulationState:
        item.circulationState === 1
          ? "待耗用"
          : item.materialStatus === 2
          ? "耗用中"
          : item.materialStatus === 3
          ? "待磨削"
          : item.materialStatus === 4
          ? "搁置"
          : item.materialStatus === 5
          ? "注销"
          : "其他",
      ...item,
    }));
  });
};

const openBusiness = (index) => {
  indexK3bm = index;
  dialogTableVisible2.value = true;
  geSysStatus();
};
const handleSizeChange2 = (val: number) => {
  geSysStatus();
};
const handleCurrentChange2 = (val: number) => {
  geSysStatus();
};
const selectedRows2 = ref([]);
const handleSelectionChange2 = (val) => {
  selectedRows2.value = val;
};
const geSysStatus = () => {
  axios({
    url: "/Gri/select/GrindingProcessStandardMain",
    method: "post",
    data: {
      ID: ID.value,
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    const definitionsList = res.data;
    tableData2.value = [];
    if (definitionsList.length == 0) {
      total2.value = 0;
      return;
    }
    total2.value = definitionsList[0].total;
    tableData2.value = definitionsList.map((item: any) => ({
      consumableCategoryName:
        item.consumableCategory === 0
          ? "辊轴类"
          : item.consumableCategory === 1
          ? "刀具类"
          : item.consumableCategory === 2
          ? "隔套类"
          : item.consumableCategory === 3
          ? "辊箱"
          : item.consumableCategory === 4
          ? "刀轴"
          : "其他",
      stateName: item.state === 0 ? "待审核" : item.state === 1 ? "已审核" : "其他",

      ...item,
    }));
  });
};

const flushed1 = () => {
  formDataList.value = [];
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};
const RowClick2 = (row, selection) => {
  form.grindingStandardMid = row.id;
  form.equipment = row.equipmentName;
  dialogTableVisible2.value = false;
};

const RowClick3 = (row) => {
  console.log(formDataList.value[indexK3bm].wlbm);
  formDataList.value[indexK3bm].componentId = row.componentId;
  formDataList.value[indexK3bm].uniqueCode = row.uniqueCode;
  formDataList.value[indexK3bm].equipmentStructureId = row.equipmentStructureId;
  axios({
    url: "/Abn/select/CurrentData",
    method: "post",
    data: {
      partSingleID: row.uniqueCode,
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    const testList = res.data;
    console.log(testList);
    if (testList.length > 0) {
      for (let a = 0; a < testList.length; a++) {
        formDataList.value[indexK3bm].material = testList[a].material;
        formDataList.value[indexK3bm].specification = testList[a].specification;
        formDataList.value[indexK3bm].model = testList[a].model;
        formDataList.value[indexK3bm].uniqueCode = testList[a].partSingleID;
        formDataList.value[indexK3bm].residualGrindingCapacity =
          testList[a].residualGrindingCapacity;
        formDataList.value[indexK3bm].roughnessStandard = testList[a].roughnessStandard;
        formDataList.value[indexK3bm].totalGrindingAmount =
          testList[a].totalGrindingAmount;
      }
      console.log(res.data);
    }
    console.log(formDataList.value);
  });
  dialogTableVisible4.value = false;
};

const windowBzfa = () => {
  dialogTableVisible5.value = true;
};
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    // #E9E9E7
    // D9D9D7   C9C9C7 A9A9A7
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};

// 查询
const searchButton = () => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/Abn/select/AbnormalApplicationMain",
      method: "post",
      data: {
        id: id.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        total.value = 0;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        autoId: test.autoId,
        id: test.id,
        djCode: test.id,
        applicant: test.applicant,
        applicationTime: test.applicationTime,
        abnormalCause: test.abnormalCause,
        exceptionMode:
          test.exceptionMode == 3 ? "搁置" : test.exceptionMode == 4 ? "异常" : "报废",
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      // form.djrq = currentFormattedDate;
      loading.value = false;
    });
  });
  loading.value = true;
};

const handleSizeChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/Abn/select/AbnormalApplicationMain",
      method: "post",
      data: {
        id: id.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        autoId: test.autoId,
        id: test.id,
        djCode: test.id,
        applicant: test.applicant,
        applicationTime: test.applicationTime,
        abnormalCause: test.abnormalCause,
        exceptionMode:
          test.exceptionMode == 3 ? "搁置" : test.exceptionMode == 4 ? "异常" : "报废",
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      loading.value = false;
    });
  });
  loading.value = true;
};
const handleCurrentChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/Abn/select/AbnormalApplicationMain",
      method: "post",
      data: {
        id: id.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        autoId: test.autoId,
        id: test.id,
        djCode: test.id,
        applicant: test.applicant,
        applicationTime: test.applicationTime,
        abnormalCause: test.abnormalCause,
        exceptionMode:
          test.exceptionMode == 3 ? "搁置" : test.exceptionMode == 4 ? "异常" : "报废",
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      // form.djrq = currentFormattedDate;
      loading.value = false;
    });
  });
  loading.value = true;
};
const updateMaterialsFixed = () => {
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  if (form.djStatus == "已审核") {
    alert("已经审核的数据不允许修改!");
    return 0;
  }
  if (form.djStatus == "") {
    alert("请选择单据状态!");
    return 0;
  }
  if (form.exceptionMode == "") {
    alert("请选择异常状态!");
    return 0;
  }
  if (form.abnormalCause == "") {
    alert("请填写异常原因!");
    return 0;
  }
  if (confirm("确认保存吗？") == false) {
    return;
  }
  const requestData = ref([]);
  formDataList.value.forEach((item, key) => {
    if (item["uniqueCode"] == "") {
      return;
    }
    requestData.value[requestData.value.length] = item;
  });
  // 显示确认弹窗
  axios({
    url: "/Abn/update/AbnormalApplication",
    method: "post",
    data: {
      id: form.id,
      abnormalCause: form.abnormalCause,
      exceptionMode:
        form.exceptionMode == "搁置" ? 3 : form.exceptionMode == "异常" ? 4 : 5,
      userName: userName,
      requestData: requestData.value,
    },
  }).then((res) => {
    if (res.data.data == 200) {
      // location.reload();
      ElMessage({
        center: true,
        showClose: true,
        grouping: true,
        offset: window.screen.height / 9,
        message: "修改成功",
        type: "success",
      });
      OFFdialogTableVisible();
      selectpurposes();
      return;
    } else if (res.data.code == 2) {
      ElMessage({
        center: true,
        showClose: true,
        grouping: true,
        offset: window.screen.height / 9,
        message: "保存失败，单件唯一码重复",
        type: "error",
      });
      selectpurposes();
      return;
    }
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "修改失败",
      type: "error",
    });
  });
};
// 新增
const insertMaterialsFixed = async () => {
  const userName = Cookies.get("userName");
  await getData(stateTable.table.currentPage);
  if (form.djStatus == "") {
    alert("请选择单据状态!");
    return 0;
  }
  if (form.exceptionMode == "") {
    alert("请选择异常状态!");
    return 0;
  }
  if (form.abnormalCause == "") {
    alert("请填写异常原因!");
    return 0;
  }
  if (confirm("确认保存吗？") == false) {
    return;
  }
  const requestData = ref([]);
  formDataList.value.forEach((item, key) => {
    if (item["uniqueCode"] == "" || item["uniqueCode"] == undefined) {
      return;
    }
    requestData.value[requestData.value.length] = item;
  });

  axios({
    url: "/Abn/insert/AbnormalApplication",
    method: "post",
    data: {
      abnormalCause: form.abnormalCause,
      exceptionMode: form.exceptionMode,
      userName: userName,
      requestData: requestData.value,
    },
  }).then((res) => {
    if (res.data.data == 200) {
      // location.reload();
      ElMessage({
        center: true,
        showClose: true,
        grouping: true,
        offset: window.screen.height / 9,
        message: "保存成功",
        type: "success",
      });
      OFFdialogTableVisible();
      selectpurposes();
      return;
    } else if (res.data.msg == 501) {
      ElMessage({
        center: true,
        showClose: true,
        grouping: true,
        offset: window.screen.height / 9,
        message: "保存失败，单件唯一码不能重复",
        type: "error",
      });
      selectpurposes();
      return;
    }
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "保存失败",
      type: "error",
    });
  });
  return;
  console.log(formDataList.value);
  // 显示确认弹窗
};
//审核

const printPage = () => {
  // 使用 window.print() 方法触发页面打印
  isPrinting.value = true;

  // Use the browser's print functionality
  window.print();

  // Reset the flag after printing is done
  isPrinting.value = false;
};
//弃审

const handleDeletes = (index: number) => {
  if (formDataList.value.length === 0) {
    addRow();
  }
  axios({
    url: "/del/WorkOrder",
    method: "post",
    data: {
      uniqueCode: formDataList.value[index].uniqueCode,
    },
  }).then((res) => {
    if (res.data.data == 200) {
      formDataList.value.splice(index, 1);
      return;
    }
    formDataList.value.splice(index, 1);
  });
};
//删除已勾选
const getDeleteRowData = () => {
  const selectedIndexes: any = [];

  // 找到已勾选行的索引
  formDataList.value.forEach((formData, index) => {
    if (formData.selected) {
      selectedIndexes.push(index);
    }
  });
  const uniqueCodesToDelete = selectedIndexes.map(
    (index) => formDataList.value[index].uniqueCode
  );
  axios({
    url: "/del/WorkOrderAll",
    method: "post",
    data: {
      uniqueCode: uniqueCodesToDelete,
    },
  }).then((res) => {
    if (res.data.data == 200) {
      // selectpurposes();
      for (let i = selectedIndexes.length - 1; i >= 0; i--) {
        formDataList.value.splice(selectedIndexes[i], 1);
      }
      // 如果没有剩余行数据，添加一行
      if (formDataList.value.length === 0) {
        addRow();
      }
      return;
    }
  });
  selectAll.value = false;
};
const toggleSelectAll = () => {
  for (const formData of formDataList.value) {
    formData.selected = selectAll.value === true;
  }
};
const handleAudit = () => {
  if (selectedRows.value.length === 0) {
    alert("请勾选需要审核的数据！");
    return;
  }
  if (selectedRows.value[0].djStatus === "已审核") {
    alert("已经审核的数据无法再次审核！");
    return;
  }
  console.log(selectedRows.value);
  if (confirm("确认审核吗？") == false) {
    return;
  }
  // .then(() => {
  const userName = Cookies.get("userName");
  axios({
    url: "/Abn/audit/AbnormalApplication",
    method: "post",
    data: {
      userName: userName,
      id: selectedRows.value.map((row) => row.id),
    },
  }).then((res) => {
    if (res.data.data == 200) {
      alert("审核成功！");
      // selectpurposes();
      selectpurposes();
      return;
    }
    ElMessage({
      showClose: true,
      message: "审核失败！",
      type: "error",
    });
  });

  // .catch(() => {});
};
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    alert("请勾选需要删除的数据！");
    return;

    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
  }
  if (confirm("确认删除吗？") == false) {
    return;
  }
  // .then(() => {
  const userName = Cookies.get("userName");
  axios({
    url: "/del/WorkOrderAudit",
    method: "post",
    data: {
      id: selectedRows.value.map((row) => row.id),
    },
  }).then((res) => {
    if (res.data.data == 200) {
      alert("删除成功！");
      selectpurposes();
      // searchButton();
      return;
    }
    ElMessage({
      showClose: true,
      message: "删除失败",
      type: "error",
    });
  });

  // .catch(() => {});
};

// 方法：获取已勾选数据
const getSelectedRowsData = () => {
  const selectedData = formDataList.value.filter((formData) => formData.selected);
  // 在这里可以执行想要的操作，例如将 selectedData 发送到服务器或者在控制台中打印出来
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
//导出数据

//导入数据

// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
selectpurposes();
interface Tree {
  label: string;
  children?: Tree[];
}

//下拉表格
const selectTable = ref();
const selectTable1 = ref();
const stateTable: any = reactive({
  table: {
    total: 0,
    currentPage: 1,
    data: [],
    columns: [
      { prop: "uniqueCode", label: "单件唯一码", width: "150", align: "center" },
      { prop: "materialCode", label: "物料编码", width: "150", align: "center" },
      {
        prop: "supplierUniqueCode",
        label: "供应商唯一码",
        width: "150",
        align: "center",
      },
    ],
  },
});
const stateTable1: any = reactive({
  table: {
    total: 0,
    currentPage1: 1,
    data: [],
    columns: [
      { prop: "uniqueCode", label: "单件唯一码", width: "150", align: "center" },
      { prop: "materialCode", label: "物料编码", width: "150", align: "center" },
      {
        prop: "supplierUniqueCode",
        label: "供应商唯一码",
        width: "150",
        align: "center",
      },
    ],
  },
});
onMounted(() => {
  getData(1);
  getData1(1);
});
const uniqueCode = ref("");
const getData = async (pageNum) => {
  const res = await crud.fetchData("/select/ComponentSingleRegistrationTable", "post", {
    page: pageNum,
    limit: 1000,
    uniqueCode: uniqueCode.value,
  });
  console.log(res);
  if (res.length == 0) {
    stateTable.table.total = 0;
    stateTable.table.data = [];
    return;
  }

  stateTable.table.data = res;
  stateTable.table.total = res[0].total;
};
const getData1 = async (pageNum) => {
  const res = await crud.fetchData("/select/ComponentRegistrationTable", "post", {
    page: pageNum,
    limit: 1000,
    uniqueCode: uniqueCode.value,
  });
  console.log(res);
  if (res.length == 0) {
    stateTable1.table.total = 0;
    return;
  }
  stateTable1.table.data = res;
  stateTable1.table.total = res[0].total;
};
// 获取当前的页码
const pageChange = (val) => {
  console.log("获取当前的页码", val);
  stateTable.table.currentPage = val;
  getData(val);
};
const pageChange1 = (val) => {
  console.log("获取当前的页码", val);
  stateTable1.table.currentPage = val;
  getData1(val);
};
const handleStatusChange = (row) => {
  let text = row.enableStatus === 1 ? "启用" : "废止";
  ElMessageBox.confirm(`确认要${text}这条数据吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log("点击确定");
    })
    .catch(() => {
      console.log("点击取消");
    });
};
const partSingleTable = (data, index) => {
  axios({
    url: "/select/CurrentDataTable",
    method: "post",
    data: {
      partSingleID: data,
      page: 1,
      limit: 10,
    },
  }).then((res) => {
    const testList = res.data;
    if (testList.length > 0) {
      for (let a = 0; a < testList.length; a++) {
        formDataList.value[index].material = testList[a].material;
        formDataList.value[index].specification = testList[a].specification;
        formDataList.value[index].model = testList[a].model;
        formDataList.value[index].uniqueCode = testList[a].partSingleID;
      }
    }
  });
};
const mnElementRange = ref("");

const selectCurrentDataTable = async (id) => {
  try {
    const res = await crud.fetchData("/Abn/select/CurrentData", "post", {
      page: stateTable.table.currentPage,
      limit: 80,
      partSingleID: id,
    });

    return res;
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const radioChange = async (row) => {
  if (Object.keys(row).length === 0) {
    return;
  }
  let cur = await selectCurrentDataTable(row.uniqueCode);
  addRow();
  for (let i = 0; i < formDataList.value.length; i++) {
    if (
      formDataList.value[i].uniqueCode == "" ||
      formDataList.value[i].uniqueCode == undefined
    ) {
      formDataList.value[i].componentId = row.componentId;
      formDataList.value[i].uniqueCode = row.uniqueCode;
      formDataList.value[i].equipmentStructureId = row.equipmentStructureId;
      formDataList.value[i].totalGrindingAmount = cur[0].totalGrindingAmount;
      formDataList.value[i].roughnessStandard = cur[0].roughnessStandard;
      formDataList.value[i].residualGrindingCapacity = cur[0].residualGrindingCapacity;
      formDataList.value[i].ljgrindingTimes = cur[0].ljgrindingTimes;
      await partSingleTable(row.uniqueCode, i);

      return;
    } else if (formDataList.value[i].uniqueCode === row.uniqueCode) {
      // Show a warning or handle the duplicate here
      notifications.showMessage("第" + (i + 1) + "单件唯一码重复", "error");
      return;
    }
  }

  selectTable.value.clear();
};
const radioChange1 = async (row) => {
  addRow();
  for (let i = 0; i < formDataList.value.length; i++) {
    if (
      formDataList.value[i].uniqueCode == "" ||
      formDataList.value[i].uniqueCode == undefined
    ) {
      formDataList.value[i].componentId = row.componentId;
      formDataList.value[i].uniqueCode = row.uniqueCode;
      formDataList.value[i].equipmentStructureId = row.equipmentStructureId;
      await partSingleTable(row.uniqueCode, i);
      return;
    } else if (formDataList.value[i].uniqueCode === row.uniqueCode) {
      // Show a warning or handle the duplicate here
      notifications.showMessage("第" + (i + 1) + "单件唯一码重复", "error");
      return;
    }
  }

  selectTable.value.clear();
};
const filterMethod = async (val) => {
  uniqueCode.value = val;
  getData(stateTable.table.currentPage);
};
const filterMethod1 = async (val) => {
  uniqueCode.value = val;
  getData1(stateTable1.table.currentPage1);
};

const handleBlurTable = () => {
  selectTable.value.clear();
};
const handleBlurTable1 = () => {
  selectTable1.value.clear();
};
const rowState1 = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
  };
};
const cellStyle1 = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    // #E9E9E7
    // D9D9D7   C9C9C7 A9A9A7

    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const headerCellStyle1 = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  // padding: "0 0 0 30px",
};
</script>

<style scoped>
@media print {
  body * {
    visibility: hidden;
  }

  .print-template,
  .print-template * {
    visibility: visible;
  }
  .print-template {
    position: absolute;
    left: -200px; /* Adjust left value to move the table to the left */
    top: 0;
    width: 100%;
  }
  /* .el-table__header-wrapper {
    display: none !important;
  } */

  /* 隐藏分页 */
  .demo-pagination-block {
    display: none !important;
  }

  /* 调整表格的位置，确保表格主体在纸张内 */
  .el-table__body-wrapper {
    margin-top: 0rem; /* 调整表格与纸张顶部的距离 */
  }
  .el-table__column--selection {
    display: none !important;
  }

  /* 将其他列向前移动一格 */
  /* .el-table__body td:nth-child(2), .el-table__header th:nth-child(2) {
  display: none !important; 
  }隐藏第二列 */

  /* .el-table__body {
  border: none !important;
} */

  /* 隐藏表格单元格的边框 */
  .el-table__body tr {
    border: none !important;
  }

  /* 隐藏表格单元格的格子 */
  /* .el-table__body td, .el-table__body th {
  border: none !important;
} */
  /* 根据需要添加更多打印样式 */
}
/* 悬停 */
::v-deep.sticky-column {
  position: sticky;
  left: 0;
  background-color: white; /* To match the parent table's background color */
  z-index: 1; /* Ensure the sticky column stays on top of other elements */
}
/* #f9f9fc, #fef5f0 */
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}
/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.custom-dialog {
  position: fixed;
  top: 12%;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 2px;
  left: 0;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 0; /* 设置横线的垂直位置，可以根据你的布局调整 */
}

.vertical-line3 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.5%; /* 设置横线的垂直位置，可以根据你的布局调整 */
  left: 0%;
}
.title {
  font-size: 18px;
}
.demo-pagination-block {
  float: right;
}
::v-deep .el-table .cell {
  padding: 0;
}
::v-deep .el-header {
  padding: 0;
}
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.buttonHeard {
  position: absolute;
  top: 0%;
  right: 1%;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}

.labs {
  margin-bottom: 0px;
}
/* 子表 */
.sticky-header {
  position: sticky;
  top: -1px;
  background-color: #ddd;
}

.table-header {
  border: 1px solid #ccc;
  background: rgb(225, 225, 230);
  /* width: 50px; */
  z-index: 99;
}

table tr td {
  /* width: 50px; */
  /* width: 10vh; */
  height: 30px;
}

table {
  border-collapse: collapse;
  border: 1px solid #ccc;
  width: 100%;
}

input {
  border: 1px solid transparent;
}

td {
  border: 1px solid #ccc;
}
#buttonmForm {
  position: absolute;
  bottom: 3px;
}
.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.4%; /* 设置横线的垂直位置，可以根据你的布局调整 */
}
.--el-dialog-padding-primary {
  padding: 0;
}
.table-value:hover {
  cursor: pointer;
  z-index: 11;
}
.red-asterisk {
  position: relative;
}
.red-asterisk::before {
  content: "*";
  color: red;
  /* position: absolute;
  left: 5px;
  top: 10px;
  margin-right: 4px; */
}
.dialogDiv {
  position: relative;
  top: 10px;
}
.flex-grow {
  flex-grow: 1;
}
.demo-basic .block:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}
.demo-basic .block {
  flex: 1;
}
::-webkit-scrollbar {
  width: 5px;
}
</style>
